<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/24
 * Time: 4:14 PM
 */
namespace app\backend\modules\sys\controllers;

use app\backend\controllers\BaseController;
use app\backend\modules\sys\services\CarouselService;
use app\common\models\Carousel;
use app\common\models\CarouselItem;

class CarouselController extends BaseController
{
    /**
     * 列表页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(){
        return view("backend.sys.carousel.index");
    }

    /**
     * 列表数据
     * @return \Illuminate\Http\JsonResponse
     */
    public function getList(){
        $search = request()->search;
        $list = (new CarouselService())->getList($search);
        return $this->successJson('',$list);
    }

    /**
     * 详情页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function detail(){
        return view("backend.sys.carousel.detail");
    }
    public function create(){
        $data = request()->params;
        $data['site_id'] = \YunCms::siteId();
        $model = new Carousel();
        $model->fill($data);
        $validator = $model->validator();
        if ($validator->fails()) {
            return $this->errorJson($validator->messages());
        } else {
            $model->save();
            return $this->successJson();
        }
    }
    public function update(){
        $data = request()->params;
        $id = $data['id'];
        $model = Carousel::find($id);
        if (empty($model)) {
            $this->errorJson('未找到数据');
        }
        $model->fill($data);
        $validator = $model->validator();
        if ($validator->fails()) {
            return $this->errorJson($validator->messages());
        } else {
            $model->save();
        }
        return $this->successJson();
    }
    /**
     * 详情数据
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDetail(){
        $id = request()->id;
        $model = Carousel::site()->select()
            ->where('id',$id)
            ->first();
        if (empty($model)) {
            return $this->errorJson('未找到数据');
        }
        return $this->successJson('',$model);
    }

    /**
     * 删除
     */
    public function delete(){
        $id = request()->id;
        $model = Carousel::find($id);
        if(!$model){
            return $this->errorJson('未找到数据');
        }
        $carouselItemCount = CarouselItem::select()
            ->where('carousel_id',$id)
            ->count();
        if($carouselItemCount>0){
            return $this->errorJson('存在幻灯片，不能删除');
        }
        $model->delete();
        return $this->successJson('');
    }
}